
/*--------------------------------------interface-------------------------------------*/

/*var localSrc = null,
 	remoteSrc = [],
	notice = ["系统公告"];*/

/*---------------------------------------system---------------------------------------*/
const common_channel = "/topic/common/message",
      private_channel = "/user/topic/private/message",
      room_channel = "/app/topic/room",
      transfer_channel = "/app/topic/transfer-msg",
      end_point = "./marcopolo",
      pcConfig = {
		'iceServers':[{
			'url':'stun:stun.l.google.com:19302'
		}]
      }

var pc = [],    //RTCPeerConnection
	localStream = null,
	remoteStream = [],
	subscription = null,
	stomp = Stomp.over(new SockJS(end_point));

stomp.connect({},function(frame){
	console.debug("连接成功");
	//订阅公共信息源
	stomp.subscribe(common_channel,handleCommonMessage);
},function(err){
	console.debug("连接出错",err);
});

function sendMsg(addr,msg){
	stomp.send(addr,{},JSON.stringify({"message":msg}));
}

/**
 *信息中转
 */
function transferMsg(msg){
	stomp.send(transfer_channel,{},JSON.stringify({"message":msg}));
}

/**
 * 加入房间
 */
function enterRoom(){
	subscription = stomp.subscribe(private_channel,handlePrivateMessage);
	console.debug("订阅描述符：",subscription);
	//发送加入房间指令
	stomp.send(room_channel);
}

/**
 * 订阅房间
 */
function subscribeRoom(){
	//订阅房间频道
	//private_channel暂时当作房间
	/*subscription = stomp.subscribe(private_channel,handlePrivateMessage);
	console.debug("订阅描述符：",subscription);*/
}

/**
 * 公共信息处理
 */
function handleCommonMessage(message){
	console.debug("handleCommonMessage",message);
	vm.notice.push(message.body);
}

/**
 * 私人信息处理
 */
function handlePrivateMessage(message){
	console.debug("handlePrivateMessage",message);
	var msg = message.body;
	switch(msg){
	case 'wait':
//		subscribeRoom();
		alert("当前房间没有人，请稍后")
		vm.notice.push("当前房间没有人，请稍后");
		break;
	case 'join':
//		subscribeRoom();
		initialize("offer");
//		createPeerConnectionAndDataChannel();
//		doCall();
		break;
	case 'full':
		alert("房间已满");
		vm.notice.push("房间已满");
		break;
	case 'end':
		closeWebRTC();
		break;
	default:
		react = JSON.parse(msg);
		switch(react.type){
		case 'offer':
			//如果不是创造者的话，接收offer
			console.debug("收到 offer 收到 offer 收到 offer");
			initialize("answer",react);
//			createPeerConnectionAndDataChannel();
//			pc[pc.length-1].setRemoteDescription(new RTCSessionDescription(react));
			//同时返回应答
//			doAnswer();
			break;
		case 'answer':
			console.debug("收到 answer 收到 answer 收到 answer");
			pc[pc.length-1].setRemoteDescription(new RTCSessionDescription(react));
			break;
		case 'candidate':
			console.debug("收到 candidate 收到 candidate 收到 candidate");
			var candidate = new RTCIceCandidate({
				sdpMLineIndex:react.label,
				sdpMind:react.id,
				candidate:react.candidate
			});
			pc[pc.length-1].addIceCandidate(candidate).then(function(e){
				console.debug("成功添加ice candidate",e);
			}).catch(function(e){
				console.debug(e);
			});
			break;
		}
		break;
	}
}

function doCall(){
	console.debug("send offer to peer");
	var rpc = pc[pc.length-1];
	rpc.createOffer(setLocalAndSendMessage, handleCreateOfferError);
}

function createPeerConnectionAndDataChannel(type){
	
	var peerConnection = new RTCPeerConnection(pcConfig);
	peerConnection.onicecandidate = handleIceCandidate;
	peerConnection.onicecandidatestatechange = onIceStateChange;
	peerConnection.onaddstream = handleRemoteStreamAdded;
	peerConnection.onremovestream = handleRemoteStreamRemoved;
	peerConnection.ondatachannel = receivehandler;
	
	/*dataChannel = pc.createDataChannel("dataChannel",dataConstraint);
	dataChannel.onopen = onSendChannelStateChange;
	dataChannel.onclose = onSendChannelStateChange;*/
	
	peerConnection.addStream(localStream);
	console.log("peerConnection",peerConnection);
	pc.push(peerConnection);
	
	if(type == "offer"){
		doCall();
	}else if(type == "answer"){
		pc[pc.length-1].setRemoteDescription(new RTCSessionDescription(react));
		doAnswer();
	}
}

/**
 * 初始化本地媒体资源
 */
function initialize(type,react){
	/*let initialize = new Promise(
		function(resolve, reject){*/
			navigator.mediaDevices.getUserMedia({
				audio:true,
				video:true
			}).then(
				function(stream){
					console.debug("initialize",stream);
					/*localSrc = window.URL.createObjectURL(stream);*/
					vm.localVideo = window.URL.createObjectURL(stream);
					localStream = stream;
					createPeerConnectionAndDataChannel(type,react);
//					resolve(local.src);
				},function(err){
//					reject(err);
					console.debug("获取媒体资源时出错",err)
			}).catch(function(e){
				console.debug("获取媒体资源时出错",e);
			});
		/*}
	);
	return initialize;*/
}  

function handleIceCandidate(event){
	console.debug("ice candidate事件被触发: ",event);
	console.debug(event.candidate);
	if(event.candidate){
		/*transferMsg(JSON.stringify(event.candidate));*/
		transferMsg(JSON.stringify({
			"type":"candidate",
			"label":event.candidate.sdpMLineIndex,
			"id":event.candidate.sdpMid,
			"candidate":event.candidate.candidate
		}));
	}else{
		console.debug("End of candidates.");
	}
}

function handleRemoteStreamAdded(event){
	console.debug("Added Remote Stream",event);
	vm.remoteVideo.push(window.URL.createObjectURL(event.stream));
//	remoteSrc.push(window.URL.createObjectURL(event.stream));
	remoteStream.push(event.stream);
}

function handleRemoteStreamRemoved(event) {
	  console.debug('Remote stream removed. Event: ', event);
}

function onIceStateChange(event){
	console.debug("Ice State has change: "+e)
}

function onSendChannelStateChange(){
	console.debug("Send Channel State has change: "+dataChannel.readyState);
}

function doAnswer(){
	console.debug("send answer to peer");
	pc[pc.length-1].createAnswer().then(
		setLocalAndSendMessage,
		onCreateSessionDescriptionError
	);
}

function handleCreateOfferError(event){
	console.debug("createOffer() error: ",event);
}

function setLocalAndSendMessage(sessionDescription) {
  // Set Opus as the preferred codec in SDP if Opus is present.
  //  sessionDescription.sdp = preferOpus(sessionDescription.sdp);
  pc[pc.length-1].setLocalDescription(sessionDescription);
  console.debug('setLocalAndSendMessage sending message', sessionDescription);
  /*sendMsg("/app/test/message",JSON.stringify(sessionDescription));*/
  transferMsg(JSON.stringify(sessionDescription));
}

function onCreateSessionDescriptionError(error) {
  console.debug('Failed to create session description: ' + error.toString());
}

function receivehandler(event){
	receiveChannel = event.channel;
	receiveChannel.onopen = onReceiveChannelStateChange;
	receiveChannel.onclose = onReceiveChannelStateChange;
	receiveChannel.onmessage = onReceiveMessageCallback;
}

function onReceiveMessageCallback(event){
	vm.verbose.push(event.data);
}

function onReceiveChannelStateChange(){
	console.debug("接受数据通道状态: "+ receiveChannel.readyState);
}

function closeWebRTC(){
	pc.close();
	pc = null;
	receiveChannel.close();
	receiveChannel = null;
	dataChannel.close();
	dataChannel = null;
} 